package com.zhss.demo.register.server;

/**
 * @Description: 自我保护策略
 * @auther: gubatian
 * @date: 2021/09/14
 */
public class SelfProtectionPolicy {
    /**
     * 期望心跳次数，如果你有10个服务实例，这个数值就是10 * 2 = 20，2是每分钟心跳一个服务实例的心跳次数
     */
    private Long expectedHeartbeatRate = 0L;
    /**
     * 期望心跳次数阈值，20 * 0.85 = 17
     */
    private Long expectedHeartbeatThreshold = 0L;
    /**
     * 阈值
     */
    public static final float HEARTBEAT_RATE_THRESHOLD = 0.85f;
    /**
     * 单例
     */
    private static SelfProtectionPolicy instance = new SelfProtectionPolicy();
    private SelfProtectionPolicy() {};
    public static SelfProtectionPolicy getInstance() {
        return instance;
    }

    public Long getExpectedHeartbeatRate() {
        return expectedHeartbeatRate;
    }

    public void setExpectedHeartbeatRate(Long expectedHeartbeatRate) {
        this.expectedHeartbeatRate = expectedHeartbeatRate;
    }

    public Long getExpectedHeartbeatThreshold() {
        return expectedHeartbeatThreshold;
    }

    public void setExpectedHeartbeatThreshold(Long expectedHeartbeatThreshold) {
        this.expectedHeartbeatThreshold = expectedHeartbeatThreshold;
    }

    /**
     * 是否开启自我保护机制
     * @return
     */
    public boolean isEnable() {
        HeartbeatMessuredRate heartbeatMessuredRate = HeartbeatMessuredRate.getInstance();
        // 获取最后一分钟心跳次数
        long latestMinuteHeartbeatRate = heartbeatMessuredRate.getLatestMinuteHeartbeatRate();
        // 心跳次数小于期望心跳次数的阈值，开启自我保护机制
        if (latestMinuteHeartbeatRate < expectedHeartbeatThreshold) {
            System.out.println("【自我保护机制开启】最近一分钟心跳次数=" + latestMinuteHeartbeatRate + ", 期望心跳次数=" + this.expectedHeartbeatThreshold);
            return true;
        }
        System.out.println("【自我保护机制未开启】最近一分钟心跳次数=" + latestMinuteHeartbeatRate + ", 期望心跳次数=" + this.expectedHeartbeatThreshold);
        return false;
    }
}
